//
//  HEHealthDetailsViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/12/8.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEHealthDetailsViewController.h"
#import "UIView+AZGradient.h"
#import "HEHealthRankModel.h"
#import "HEHealthDetailRanderModel.h"
#import "HEHealthDetailItemCell.h"

@import Charts;
@import SwiftCus;

@interface HEHealthDetailsViewController ()<ChartViewDelegate, ChartAxisValueFormatter, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) RadarChartView *chartView;
@property (nonatomic, strong) NSMutableArray<NSString *> *activities;
@property (nonatomic, strong) UIColor *originalBarBgColor;
@property (nonatomic, strong) UIColor *originalBarTintColor;
@property (nonatomic) UIBarStyle originalBarStyle;

@property (nonatomic, strong) HEHealthDetailRanderModel *details;
@property (nonatomic, assign) CGFloat mult;
@property (nonatomic, strong) UILabel *centerLb;

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray * dataSourceArr;
@property (nonatomic, assign) CGFloat chartHeight;

@end

@implementation HEHealthDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"健康详请";
    
    [self setupNav];
    
    _chartHeight = 260;
    [self setCustomTableView:self.tableView];
    [self.view addSubview: _tableView];

    _dataSourceArr = [NSMutableArray array];
    [self initChart];

    [self loadData];
}

- (void)setupNav {
    // 设置导航栏按钮
    [self zx_setRightBtnWithImgName:@"help" clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        [WOAlert alertShowTitle:@"温馨提示" message:@"标红的数值为低于平均水平的健康值，该数值依据健康指标数据及健康量表结果，根据权威计算方式计算所得。" cancelButtonTitle:@"确定" otherButtonTitles:nil block:^(NSInteger buttonIndex) {
            
        }];
    }];
}

- (void)loadData {
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KhealthGroup parameters:@{} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues: responseObject];
        [self.tableView.mj_header endRefreshing];

        self.details = [HEHealthDetailRanderModel mj_objectWithKeyValues: response.data];

        [self updateChartData];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (GDTableView *)tableView {
   if (!_tableView) {
       _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight + _chartHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight - _chartHeight) style:UITableViewStyleGrouped];
       _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       _tableView.scrollsToTop = YES;
       _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
       _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

       _tableView.showsVerticalScrollIndicator = NO;
       _tableView.backgroundColor = CViewBgColor;
       _tableView.delegate = self;
       _tableView.dataSource = self;
       
       __weak __typeof(&*self)weakSelf = self;
       self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
           [weakSelf loadData];
       }];
         
       [_tableView registerClass:[HEHealthDetailItemCell class] forCellReuseIdentifier: KHEHealthDetailItemCell];
   }
   return _tableView;
}


- (void)initChart {
    UIView *chartWarp = [UIView new];
    chartWarp.backgroundColor = UIColor.orangeColor;
    [chartWarp az_setGradientBackgroundWithColors:@[KHexColor(@"#5B86E5"), KHexColor(@"#32b1dc")] locations:nil startPoint:CGPointMake(0, 0) endPoint:CGPointMake(0, 1)];
    [self.view addSubview:chartWarp];
    [chartWarp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(ZXNavBarHeight);
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(-0);
        make.height.offset(_chartHeight);
    }];
    
    self.activities = @[].mutableCopy;

    _chartView = [[RadarChartView alloc] initWithFrame: CGRectZero];
    [chartWarp addSubview:_chartView];
    [_chartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(chartWarp).offset(10);
        make.left.equalTo(chartWarp);
        make.right.equalTo(chartWarp);
        make.height.equalTo(chartWarp);
    }];
    
    // 中心点
    _centerLb = [UILabel new];
    _centerLb.font = DYFont(16);
    _centerLb.textColor = CNavBgColor;
    _centerLb.textAlignment = NSTextAlignmentCenter;
    _centerLb.userInteractionEnabled = NO;
    [chartWarp addSubview:_centerLb];
    [_centerLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(chartWarp);
        make.centerY.equalTo(chartWarp);
        make.width.offset(200);
//        make.height.equalTo(chartWarp);
    }];
    
    
    _chartView.delegate = self;
    _chartView.chartDescription.enabled = NO;
    _chartView.webLineWidth = 1.0;
    _chartView.innerWebLineWidth = 1.0;
    _chartView.webColor = KWhiteColor;
    _chartView.innerWebColor = KWhiteColor;
    _chartView.webAlpha = 1.0;
    _chartView.legend.enabled = NO;
    _chartView.minOffset = 20; // 内边距
    _chartView.noDataText = @"暂无数据";
    _chartView.noDataTextColor = KWhiteColor;

    RadarMarkerView *marker = [[RadarMarkerView alloc] init];
    marker.chartView = _chartView;
    _chartView.marker = marker;
    
    ChartXAxis *xAxis = _chartView.xAxis;
    xAxis.labelFont =  DYFont(14);
    xAxis.xOffset = 0.0;
    xAxis.yOffset = 0.0;
    xAxis.valueFormatter = self;
    xAxis.labelTextColor = UIColor.whiteColor;
    
    ChartLegend *l = _chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentCenter;
    l.verticalAlignment = ChartLegendVerticalAlignmentTop;
    l.orientation = ChartLegendOrientationHorizontal;
    l.drawInside = NO;
    l.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    l.xEntrySpace = 7.0;
    l.yEntrySpace = 5.0;
    l.textColor = UIColor.whiteColor;
    
//    [self updateChartData];
    
    [_chartView animateWithXAxisDuration:1.4 yAxisDuration:1.4 easingOption:ChartEasingOptionEaseOutBack];
}

- (void)updateChartData
{
    
    self.activities = @[].mutableCopy;
    
    for (HEHealthNodeModel *item in _details.healthNode) {
        [self.activities addObject: item.health_name];
    }
    [self.dataSourceArr removeAllObjects];
    [_dataSourceArr addObjectsFromArray: _details.healthParams];
    [self.tableView reloadData];
    
    [self setChartData];
}

- (void)setChartData
{
 
    NSMutableArray *entries1 = [[NSMutableArray alloc] init];
  
    _mult = 0;
    CGFloat sum = 0;
    for (HEHealthNodeModel *item in _details.healthNode) {
        _mult = MAX(item.max_value, _mult);
    }
    
    int i = 0;
    for (HEHealthNodeModel *item in _details.healthNode) {
        _mult = MAX(item.max_value, _mult);
        CGFloat itemValue = (item.health_value.floatValue / item.max_value) * _mult;
        sum += item.health_value.floatValue;
        [entries1 addObject:[[RadarChartDataEntry alloc] initWithValue:itemValue data:item]];
    }
    
    _centerLb.text = [NSString stringWithFormat:@"%.2f", sum];
    
    ChartYAxis *yAxis = _chartView.yAxis;
    yAxis.labelFont = DYFont(14);
    yAxis.labelCount = 5;
    yAxis.axisMinimum = 0.0;
    yAxis.axisMaximum = _mult;
    yAxis.drawLabelsEnabled = NO;
    
    RadarChartDataSet *set1 = [[RadarChartDataSet alloc] initWithEntries:entries1 label:@"Last Week"];
    [set1 setColor:KWhiteColor];
    set1.fillColor = KWhiteColor;
    set1.drawFilledEnabled = YES;
    set1.fillAlpha = 1;
    set1.lineWidth = 2.0;
    set1.drawHighlightCircleEnabled = YES;
    [set1 setDrawHighlightIndicators:NO];
    
    RadarChartData *data = [[RadarChartData alloc] initWithDataSets:@[set1]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:8.f]];
    [data setDrawValues:NO];
    data.valueTextColor = UIColor.whiteColor;
    
    _chartView.data = data;
}

#pragma mark - ChartViewDelegate

- (void)chartValueSelected:(ChartViewBase * __nonnull)chartView entry:(ChartDataEntry * __nonnull)entry highlight:(ChartHighlight * __nonnull)highlight
{
    HEHealthNodeModel *item = entry.data;
    NSInteger section = 0;
    for (int i = 0; i < self.activities.count; i++) {
        if ([item.health_name isEqualToString:self.activities[i]]) {
            section = i;
            break;
        }
    }
    NSLog(@"chartValueSelected   *%ld", section);
    [self.tableView scrollToRow:0 inSection: section atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)chartValueNothingSelected:(ChartViewBase * __nonnull)chartView
{
    NSLog(@"chartValueNothingSelected");
}

#pragma mark - IAxisValueFormatter

- (NSString *)stringForValue:(double)value
                        axis:(ChartAxisBase *)axis
{
    NSInteger i = (int) value % self.activities.count;
    HEHealthNodeModel *item = _details.healthNode[i];
    return [NSString stringWithFormat:@"%@\n%@", self.activities[i], item.health_value];
}
    
#pragma mark - UITableViewDataSource
 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSourceArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    HEHealthDetailPramaModel *itemModel = self.dataSourceArr[section];
    return itemModel.list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HEHealthDetailItemCell *cell = [_tableView dequeueReusableCellWithIdentifier: KHEHealthDetailItemCell];
    
    HEHealthDetailPramaModel *itemModel = self.dataSourceArr[indexPath.section];
    cell.model = itemModel.list[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HEHealthDetailPramaModel *itemModel = self.dataSourceArr[indexPath.section];
    HEHealthNodeModel *model = itemModel.list[indexPath.row];
    return [tableView fd_heightForCellWithIdentifier: KHEHealthDetailItemCell cacheByIndexPath:indexPath configuration:^(HEHealthDetailItemCell *cell) {
        cell.model = model;
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 46;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    HEHealthDetailPramaModel *itemModel = self.dataSourceArr[section];

    UIView *headView = [UIView new];
    
    UIView *dotView = [UIView new];
    dotView.backgroundColor = CNavBgColor;
    [headView addSubview:dotView];
    dotView.layer.cornerRadius = 5;
    
    UILabel *nameLb = [UILabel new];
    nameLb.font = DYFont(16);
    nameLb.textColor = CNavLightBlackColor;
    [headView addSubview:nameLb];
    nameLb.text = itemModel.name;
    
    [dotView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(headView);
        make.left.equalTo(headView).mas_offset(15);
        make.width.height.mas_offset(10);
    }];
    
    [nameLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(headView);
        make.left.equalTo(dotView.mas_right).mas_offset(10);
        make.right.equalTo(headView).mas_offset(-15);
    }];
    
    return headView;
}

@end
